<template>
  <div class="app-container">
    <div class="filter-container">
      <el-form ref="tableForm" :inline="true" :model="listQuery">
        <el-row>
          <el-col :span="4">
            <el-form-item label="商品标题" prop="product_title">
              <el-input
                v-model="listQuery.product_title"
                @keyup.enter.native="handleFilter"
              />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="商品ID" prop="product_id">
              <el-input
                v-model="listQuery.product_id"
                @keyup.enter.native="handleFilter"
              />
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="添加时间" prop="created_at">
              <el-date-picker
                v-model="listQuery.created_at"
                value-format="yyyy-MM-dd HH:mm:ss"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="状态" prop="status">
              <el-select v-model="listQuery.status" placeholder="请选择">
                <el-option label="有效" :value="1" />
                <el-option label="禁用" :value="2" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="推荐状态" prop="is_recommend">
              <el-select v-model="listQuery.is_recommend" placeholder="请选择">
                <el-option label="推荐" :value="1" />
                <el-option label="不推荐" :value="2" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="4">
            <el-form-item label="计划ID" prop="promotion_id">
              <el-input
                v-model="listQuery.promotion_id"
                @keyup.enter.native="handleFilter"
              />
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="是否热门" prop="is_hot">
              <el-select v-model="listQuery.is_hot" placeholder="请选择">
                <el-option label="是" :value="1" />
                <el-option label="否" :value="2" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-button @click="resetForm('tableForm')">重置</el-button>
            <el-button
              v-waves
              type="primary"
              icon="el-icon-search"
              @click="handleFilter"
            >
              {{ $t("table.search") }}
            </el-button>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <el-button type="success" class="marginBm" @click="handleAdd"
      >添加商品</el-button
    >
    <el-button type="danger" class="marginBm" @click="editAll(1)"
      >批量删除</el-button
    >
    <el-button type="warning" class="marginBm" @click="editAll(2)"
      >批量下架</el-button
    >
    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%"
      @sort-change="sortChange"
      @selection-change="selectionChange"
    >
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column
        label="商品信息"
        prop="nickname"
        align="center"
        width="300"
      >
        <template slot-scope="{ row }">
          <div class="goodsInfo">
            <el-avatar
              :src="row.product_image"
              :size="50"
              fit="contain"
              shape="square"
            />
            <div class="textBox">
              <el-tooltip
                effect="dark"
                placement="top"
                :content="row.product_title"
              >
                <div class="content">商品标题：{{ row.product_title }}</div>
              </el-tooltip>
              <div class="content">计划ID：{{ row.promotion_id }}</div>
              <div class="content">佣金比例：{{ row.commission_rate }}</div>
              <div class="content">商品ID：{{ row.product_id }}</div>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="价格信息" prop="product_price" align="center" />
      <el-table-column label="补贴金额" prop="subsidy_amount" align="center" />
      <el-table-column
        label="活动开始时间"
        prop="start_time"
        align="center"
        width="170"
      >
        <template slot-scope="{ row }">
          <span>{{ row.start_time || "-" }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="活动到期时间"
        prop="end_time"
        align="center"
        width="170"
      >
        <template slot-scope="{ row }">
          <span>{{ row.end_time || "-" }}</span>
        </template>
      </el-table-column>
      <el-table-column label="发布状态" prop="status" align="center">
        <template slot-scope="{ row }">
          {{ row.status | statusFilter }}
        </template>
      </el-table-column>
      <el-table-column label="商品状态" prop="account_balance" align="center">
        <template slot-scope="{ row }">
          <el-switch
            v-model="row.status"
            :active-value="1"
            :inactive-value="2"
            @change="handleStatuChange($event, row.id)"
          />
        </template>
      </el-table-column>
      <el-table-column label="是否热门" prop="is_hot" align="center">
        <template slot-scope="{ row }">
          <el-switch
            v-model="row.is_hot"
            :active-value="1"
            :inactive-value="2"
            @change="handleHotChange($event, row.id)"
          />
        </template>
      </el-table-column>
      <el-table-column label="列表排序" prop="order_num" align="center" />
      <el-table-column
        :label="$t('table.actions')"
        align="center"
        width="230"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="{ row }">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button type="danger" size="mini" @click="handleDelete(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />

    <el-dialog
      :title="textMap[dialogStatus]"
      center
      :visible.sync="dialogFormVisible"
      :close-on-click-modal="false"
    >
      <el-form ref="dataForm" :model="temp" label-width="110px" :rules="rules">
        <el-row>
          <el-col :span="12">
            <el-form-item label="商品链接" prop="product_link">
              <div class="flexBox">
                <el-input v-model="temp.product_link" />
                <el-button
                  class="btn"
                  type="primary"
                  size="mini"
                  :disabled="!temp.product_link"
                  @click="handleDetail(temp.product_link)"
                >
                  获取详情
                </el-button>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="主图">
              <el-upload
                class="avatar-uploader"
                :action="baseUrl + '/upload'"
                :show-file-list="false"
                :headers="headers"
                name="image"
                :on-success="handleTopSuccess"
              >
                <img
                  v-if="temp.product_image"
                  :src="temp.product_image"
                  class="avatar"
                />
                <i v-else class="el-icon-plus avatar-uploader-icon" />
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="选择分类">
              <el-select v-model="temp.product_category" class="filter-item">
                <el-option
                  v-for="item in statusOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id + ''"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="商品标题" prop="product_title">
              <el-input v-model="temp.product_title" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="短标题" prop="product_short_title">
              <el-input v-model="temp.product_short_title" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="推广文案" prop="product_content">
              <el-input
                v-model="temp.product_content"
                :autosize="{ minRows: 2, maxRows: 4 }"
                type="textarea"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <div class="baseLine" />
        <el-row>
          <el-col :span="8">
            <el-form-item label="原价" prop="product_price">
              <el-input v-model="temp.product_price" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="优惠券" prop="product_coupon">
              <el-input
                v-model="temp.product_coupon"
                @blur="handleCouponChange"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="券后价" prop="post_coupon_price">
              <el-input v-model="temp.post_coupon_price" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="佣金比例" prop="commission_rate">
              <el-input v-model="temp.commission_rate" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="库存" prop="product_stock">
              <el-input v-model="temp.product_stock" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="推广计划ID" prop="promotion_id">
              {{ temp.promotion_id }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="补贴" prop="subsidy_amount">
              <el-input v-model="temp.subsidy_amount" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="直推补贴金额" prop="push_subsidy_amount">
              <el-input v-model="temp.push_subsidy_amount" />
            </el-form-item>
          </el-col>
        </el-row>
        <div class="baseLine" />
        <el-row>
          <el-col :span="12">
            <el-form-item label="列表排序" prop="order_num">
              <el-input-number
                v-model="temp.order_num"
                :min="1"
                :max="99"
                :controls="false"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否热门" prop="is_hot">
              <el-switch
                v-model="temp.is_hot"
                :active-value="1"
                :inactive-value="2"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="活动开始时间" prop="start_time">
              <el-date-picker
                v-model="temp.start_time"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="活动结束时间" prop="end_time">
              <el-date-picker
                v-model="temp.end_time"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="发布状态" prop="status">
              <el-radio-group v-model="temp.status">
                <el-radio :label="1"> 发布 </el-radio>
                <el-radio :label="3"> 定时发布 </el-radio>
              </el-radio-group>
              <el-date-picker
                v-if="temp.status == 3"
                v-model="temp.publish_time"
                value-format="yyyy-MM-dd HH:mm:ss"
                style="margin-left: 20px"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="用户展示" prop="user_show">
              <el-radio-group v-model="temp.user_show">
                <el-radio :label="1">所有人</el-radio>
                <el-radio :label="2">指定用户</el-radio>
              </el-radio-group>
              <el-select
                v-show="temp.user_show != 1"
                v-model="temp.user_rids"
                style="margin-left: 20px"
                multiple
                filterable
                remote
                reserve-keyword
                placeholder="请输入关键词"
                :remote-method="searchComment"
              >
                <el-option
                  v-for="item in commentList"
                  :key="item.id"
                  :label="item.nickname"
                  :value="item.rid"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          {{ $t("table.cancel") }}
        </el-button>
        <el-button type="primary" @click="updateData()">
          {{ $t("table.confirm") }}
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  fetchProductList,
  fetchLevelList,
  productEdit,
  fetchCateList,
  productMarket,
  productUpdate,
  commentUserList,
} from "@/api/index";
import waves from "@/directive/waves"; // waves directive
import Pagination from "@/components/Pagination"; // secondary package based on el-pagination
import { getToken } from "@/utils/auth";

export default {
  components: { Pagination },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        1: "已发布",
        2: "已下架",
        3: "待发布",
      };
      return statusMap[status];
    },
  },
  data() {
    return {
      selectionList: [],
      commentList: [],
      rules: {
        start_time: [
          {
            type: "string",
            required: true,
            message: "请选择开始时间",
            trigger: "change",
          },
        ],
        end_time: [
          {
            type: "string",
            required: true,
            message: "请选择结束时间",
            trigger: "change",
          },
        ],
      },
      baseUrl: process.env.VUE_APP_BASE_API,
      headers: {
        "access-token": getToken(),
      },
      activeName: "1",
      orderName: "share",
      tableKey: 0,
      levelUserList: null,
      list: null,
      orderList: null,
      total: 0,
      userTotal: 0,
      orderTotal: 0,
      listLoading: false,
      userListQuery: {
        page: 1,
        limit: 10,
      },
      listQuery: {
        page: 1,
        limit: 20,
      },
      orderListQuery: {
        page: 1,
        limit: 10,
      },
      sortOptions: [
        { label: "ID Ascending", key: "+id" },
        { label: "ID Descending", key: "-id" },
      ],
      statusOptions: [],
      showReviewer: false,
      temp: {
        product_id: null,
        product_link: "",
        product_title: "",
        product_short_title: null,
        product_description: "",
        product_content: "",
        product_category: "",
        product_image: "",
        product_price: "",
        product_coupon: null,
        post_coupon_price: null,
        product_stock: null,
        subsidy_amount: "",
        push_subsidy_amount: "",
        publish_time: "",
        start_time: null,
        end_time: null,
        order_num: null,
        is_recommend: 2,
        is_hot: 2,
        status: 1,
        deleted_at: null,
        anchor_id: null,
        commission_rate: "",
        commission_type: null,
        is_living: 0,
        live_start_time: null,
        live_id: 0,
        promotion_id: null,
        second_category: "",
        partner_ratio: "",
        platform_fee: "0",
        created_at: "",
        updated_at: "",
        user_show: 1,
        user_rids: "",
      },
      dialogFormVisible: false,
      dialogStatus: "",
      textMap: {
        update: "编辑商品",
        create: "添加商品",
      },
      dialogPvVisible: false,
      pvData: [],
      downloadLoading: false,
    };
  },
  created() {
    this.getList();
    this.getCateList();
    this.getcommentUserList();
  },
  methods: {
    editAll(type) {
      let item = this.selectionList;
      item = item.toString();
      let temp = {};
      if (type == 1) {
        temp = {
          id: item,
          type: 3,
        };
      } else {
        temp = {
          id: item,
          type: 1,
          status: 2,
        };
      }
      productUpdate(temp).then(() => {
        this.$message.success("操作成功");
        this.getList();
      });
    },
    selectionChange(value) {
      this.selectionList = value.map((item) => {
        return item.id;
      });
    },
    searchComment(data) {
      commentUserList({
        search_key: data,
      }).then((res) => {
        this.commentList = res.data;
      });
    },
    getcommentUserList() {
      commentUserList().then((res) => {
        this.commentList = res.data;
      });
    },
    handleCouponChange() {
      if (this.temp.product_price && this.temp.product_coupon) {
        this.temp = Object.assign({}, this.temp, {
          post_coupon_price: (
            this.temp.product_price - this.temp.product_coupon
          ).toFixed(2),
        });
      }
    },
    handleStatuChange(val, id) {
      productUpdate({ id, type: 1, status: val }).then(() => {
        this.getList();
      });
    },
    handleHotChange(val, id) {
      productUpdate({ id, type: 2, is_hot: val }).then(() => {
        this.getList();
      });
    },
    handleRecommendChange(val, id) {
      productUpdate({ id, type: 2, is_recommend: val }).then(() => {
        this.getList();
      });
    },
    handleDetail(object_ids) {
      productMarket({ object_ids }).then((response) => {
        this.$nextTick(() => {
          this.temp = Object.assign({}, this.temp, response.data[0]);
        });
      });
    },
    handleAdd() {
      this.dialogStatus = "create";
      this.temp = {
        product_id: null,
        product_link: "",
        product_title: "",
        product_short_title: null,
        product_description: "",
        product_content: "",
        product_category: "",
        product_image: "",
        product_price: "",
        product_coupon: null,
        post_coupon_price: null,
        product_stock: null,
        subsidy_amount: "",
        push_subsidy_amount: "",
        publish_time: "",
        start_time: null,
        end_time: null,
        order_num: null,
        is_recommend: 2,
        is_hot: 2,
        status: 1,
        deleted_at: null,
        anchor_id: null,
        commission_rate: "",
        commission_type: null,
        is_living: 0,
        live_start_time: null,
        live_id: 0,
        promotion_id: null,
        second_category: "",
        partner_ratio: "",
        platform_fee: "0",
        created_at: "",
        updated_at: "",
        user_show: 1,
        user_rids: [],
      };
      this.dialogFormVisible = true;
    },
    handleTopSuccess(res, file) {
      if (res.code === 200) {
        this.temp = Object.assign({}, this.temp, {
          product_image: res.data.image,
        });
      } else {
        this.$message.error(res.msg);
      }
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    getList() {
      const params = JSON.parse(JSON.stringify(this.listQuery));
      if (params.created_at && params.created_at.length) {
        params.created_at = params.created_at.join(",");
      } else {
        params.created_at = "";
      }
      this.listLoading = true;
      fetchProductList(params).then((response) => {
        this.list = response.data.list;
        this.total = response.data.total;
        this.listLoading = false;
      });
    },
    getCateList() {
      fetchCateList({ type: 1 }).then((response) => {
        this.statusOptions = response.data.list;
      });
    },
    getUserList() {
      fetchLevelList({
        ...this.userListQuery,
        id: this.temp.id,
      }).then((response) => {
        this.levelUserList = response.data.users;
        this.userTotal = response.data.total;
      });
    },
    handleFilter() {
      this.listQuery.page = 1;
      this.getList();
    },
    sortChange(data) {
      const { prop, order } = data;
      if (prop === "id") {
        this.sortByID(order);
      }
    },
    sortByID(order) {
      if (order === "ascending") {
        this.listQuery.sort = "+id";
      } else {
        this.listQuery.sort = "-id";
      }
      this.handleFilter();
    },
    handleUpdate(row) {
      commentUserList().then((res) => {
        this.commentList = res.data;
        this.temp = JSON.parse(JSON.stringify(row));
        if (this.temp.user_rids != "" && this.temp.user_rids) {
          this.temp.user_rids = row.user_rids.split(",");
          this.temp.user_rids = this.temp.user_rids.map(Number);
        }
        this.dialogFormVisible = true;
      });
    },
    handleDelete(row) {
      this.$confirm("是否确认删除?", "提示", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          await productUpdate({
            id: row.id,
            type: 3,
          });
          this.$message({
            type: "success",
            message: "操作成功",
          });
          this.getList();
        })
        .catch((err) => {
          console.error(err);
        });
    },
    updateData() {
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          const tempList = JSON.parse(JSON.stringify(this.temp));
          if (tempList.user_show == 2) {
            tempList.user_rids = tempList.user_rids.toString();
          }
          productEdit(tempList).then(() => {
            this.$message({ message: "操作成功", type: "success" });
            this.dialogFormVisible = false;
            this.getList();
          });
        }
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.flexBox {
  display: flex;
  .btn {
    margin-left: 20px;
  }
}
.baseLine {
  width: 100%;
  height: 1px;
  background-color: #ccc;
  margin-bottom: 22px;
}
.filter-container {
  border-bottom: 1px solid #ccc;
  margin-bottom: 20px;
}
.marginBm {
  margin-bottom: 20px;
}
.dataBox {
  padding: 20px 0;
  border-top: 1px solid #333;
  display: flex;
  .item {
    flex: 1;
  }
}
.avatar-uploader {
  ::v-deep .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    &:hover {
      border-color: #409eff;
    }
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
}
.goodsInfo {
  display: flex;
  align-items: center;
  .textBox {
    text-align: left;
    margin-left: 10px;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    .content {
      width: 200px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }
}
</style>
